package com.dmgis.qxfw.dataservice.businessservice.nyfw.service.Impl;

import com.dmgis.qxfw.dataservice.businessservice.api.domain.DbConfig;
import com.dmgis.qxfw.dataservice.businessservice.api.domain.RequestDataBySelect;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.ny.*;
import com.dmgis.qxfw.dataservice.businessservice.common.domain.ResultObj;
import com.dmgis.qxfw.dataservice.businessservice.common.util.FileUtil;
import com.dmgis.qxfw.dataservice.businessservice.common.util.JsonUtil;
import com.dmgis.qxfw.dataservice.businessservice.common.util.StringUtil;
import com.dmgis.qxfw.dataservice.businessservice.controller.ProcessRequestController;
import com.dmgis.qxfw.dataservice.businessservice.dmgis_mongodb_srv.dataservice.service.Impl.MongoService1;
import com.dmgis.qxfw.dataservice.businessservice.nyfw.service.FarmXxfwService;
import com.fasterxml.jackson.core.type.TypeReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName FarmXxfwServiceImpl
 * @Description TODO
 * @Author sun
 * @Date 2021/7/26 14:50
 * @Version 1.0
 **/
@Service("FarmXxfwService")
public class FarmXxfwServiceImpl implements FarmXxfwService {
    private  final String operatingSystem;

    @Autowired
    public FarmXxfwServiceImpl(String operatingSystem) {
        this.operatingSystem = operatingSystem;
    }
    ProcessRequestController pc = new ProcessRequestController();
    MongoService1 ms = new MongoService1();

    @Override
    public Object getFwStationInfo(String stationID, String tiaojian, HttpServletRequest request) {
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        Map<String, String> selectParam = new HashMap<>();
        List<StationInfo> infoList = new ArrayList<>();
        try {
            StringBuilder builder = new StringBuilder();
            builder.append("lon != -1");
            if (!StringUtil.IsNullOrEmpty(stationID))
                builder.append(" and stationid = '" + stationID + "'");
            if (!StringUtil.IsNullOrEmpty(tiaojian)) {
                builder.append(" and (stationid like '%" + tiaojian + "%'");
                builder.append(" or stationname like '%" + tiaojian + "%'");
                builder.append(" or township like '%" + tiaojian + "%'");
                builder.append(" or county like '%" + tiaojian + "%'");
                builder.append(" or smallscalestationid like '%" + tiaojian + "%')");
            }
            selectRequest.setParam(builder.toString());
            selectParam.put("method", "station_info");
            selectParam.put("sqlType", "select");
            selectParam.put("advCode", DbConfig.advCode);
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            infoList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<StationInfo>>() {
            });
            if (infoList.size() != 0) {
                for (StationInfo info : infoList) {
                    if (info.getPic().trim() != "") {
                        String servicePath = "";// 服务器文件
                        String urlpath ;
                        if (operatingSystem.equals("Windows")){
                             urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\Nongchang\\";// 临时文件目录
                        }else {
                             urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/Nongchang/";// 临时文件目录
                        }

                        FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
                        FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
                        String fileName = info.getPic().trim();// 文件名
                        String jpgPath = urlpath + fileName;
                        File jpgFile = new File(jpgPath);
                        if (jpgFile.exists()) {
                            if (operatingSystem.equals("Windows")){
                                servicePath = "Temp\\Nongchang\\" + fileName;
                            }else {
                                servicePath = "Temp/Nongchang/" + fileName;
                            }

                            String path = request.getContextPath();
                            info.setPic(DbConfig.IP + path + "/" + servicePath.replace("\\", "/"));
                        } else {
                            Map<String, Object> map = new HashMap<String, Object>();
                            map.put("stationid", info.getStationid());
                            map.put("table_name", "station_info");
                            map.put("collectionName", "image_file");
                            map.put("advCode", DbConfig.advCode);
                            byte[] data = ms.selectData(map);
                            if (data == null) {
                                info.setPic("");
                            } else {
                                FileUtil.bytesToFile(data, jpgPath);
                                String path = request.getContextPath();
                                info.setPic(DbConfig.IP + path + "/" + servicePath.replace("\\", "/"));
                            }
                        }
                    }
                    String strtext = "预报站点编号:" + info.getForecaststationid() + " 所属乡镇:" + info.getTownship() + " 主要农作物:" + info.getMaincrop() + " 基本情况:" + info.getBasicsituation();
                    info.setBasicsituation(strtext);
                }
            }
        } catch (Exception ex) {
            return new ResultObj("查询失败!", ex.getMessage(), false);
        }
        return new ResultObj("查询成功!", infoList, true);
    }

    /**
     * @Description: 大户统计
     * @Author: sunshine
     * @Date: 2021/7/26 15:49
     **/
    @Override
    public Object getDaHuTongji(String strType) {
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        Map<String, String> selectParam = new HashMap<>();
        List<StationInfo> infoList = new ArrayList<>();
        try {
            if (strType.equals("区县")) {
                selectRequest.setColumns(new String[]{"count(*) as stationid", "county"});
                selectParam.put("method", "station_info");
                selectParam.put("sqlType", "select");
                selectParam.put("advCode", DbConfig.advCode);
                selectParam.put("param", JsonUtil.object2Json(selectRequest));
                String message = pc.processRequest(selectParam);
                infoList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<StationInfo>>() {
                });
                List<stationsum> list1 = new ArrayList<>();
                for (StationInfo info : infoList) {
                    stationsum sum = new stationsum();
                    sum.setType(info.getCounty());
                    sum.setNum(info.getStationid());
                    list1.add(sum);
                }
                return new ResultObj("查询成功!", list1, true);
            } else {
                selectRequest.setColumns(new String[]{"count(*) as stationid", "maincrop"});
                selectRequest.setParam("maincrop ='甘蔗'" + " or maincrop ='玉米'" + " or maincrop ='水稻'" + " or maincrop ='香蕉'" + " or maincrop ='茉莉花'" + " or maincrop ='桑蚕'");
                selectParam.put("method", "station_info");
                selectParam.put("sqlType", "select");
                selectParam.put("advCode", DbConfig.advCode);
                selectParam.put("param", JsonUtil.object2Json(selectRequest));
                String message = pc.processRequest(selectParam);
                infoList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<StationInfo>>() {
                });
                List<stationsum> list1 = new ArrayList<>();
                for (StationInfo info : infoList) {
                    stationsum sum = new stationsum();
                    sum.setType(info.getMaincrop());
                    sum.setNum(info.getStationid());
                    list1.add(sum);
                }
                return new ResultObj("查询成功!", list1, true);
            }
        } catch (Exception ex) {
            return new ResultObj("查询失败!", ex.getMessage(), false);
        }
    }

    /**
     * @Description: 产量预报
     * @Author: sunshine
     * @Date: 2021/7/27 10:40
     **/
    @Override
    public Object getnyclyb(String strtybh) {
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        Map<String, String> selectParam = new HashMap<>();
        List<CropyieldHistory> infoList = new ArrayList<>();
        try {
            selectRequest.setColumns(new String[]{" distinct cropname"});
            if (!StringUtil.IsNullOrEmpty(strtybh))
                selectRequest.setParam("stationid = '" + strtybh + "'");
            selectParam.put("method", "cropyield_history");
            selectParam.put("sqlType", "select");
            selectParam.put("advCode", DbConfig.advCode);
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            infoList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<CropyieldHistory>>() {
            });
        } catch (Exception ex) {
            return new ResultObj("查询失败!", ex.getMessage(), false);
        }
        return new ResultObj("查询成功!", infoList, true);
    }

    /**
     * @Description: 产量预报-根据农作物得到作物品种
     * @Author: sunshine
     * @Date: 2021/7/27 10:47
     **/
    @Override
    public Object getZwTypeByName(String strtybh, String cropname) {
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        Map<String, String> selectParam = new HashMap<>();
        List<CropyieldHistory> infoList = new ArrayList<>();
        try {
            selectRequest.setColumns(new String[]{" distinct type"});
            StringBuilder builder = new StringBuilder();
            builder.append("1=1");
            if (!StringUtil.IsNullOrEmpty(cropname))
                builder.append(" and cropname = '" + cropname + "'");
            if (!StringUtil.IsNullOrEmpty(strtybh))
                builder.append(" and stationid = '" + strtybh + "'");
            selectRequest.setParam(builder.toString());
            selectParam.put("method", "cropyield_history");
            selectParam.put("sqlType", "select");
            selectParam.put("advCode", DbConfig.advCode);
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            infoList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<CropyieldHistory>>() {
            });
        } catch (Exception ex) {
            return new ResultObj("查询失败!", ex.getMessage(), false);
        }
        return new ResultObj("查询成功!", infoList, true);
    }

    /**
     * @Description: 得到产量预报
     * @Author: sunshine
     * @Date: 2021/7/27 10:52
     **/
    @Override
    public Object getChangliangYb(String strtybh, String cropname, String year, String yearend, String type) {
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        ArrayList arrayList = new ArrayList();
        Map<String, String> selectParam = new HashMap<>();
        List<CropyieldHistory> infoList = new ArrayList<>();
        if (StringUtil.IsNullOrEmpty(year) || StringUtil.IsNullOrEmpty(yearend))
            return new ResultObj("查询失败!", "年份不能为空!", false);
        try {
            List<String> times = new ArrayList<>();
            List<Double> history = new ArrayList<>();
            List<Double> fast = new ArrayList<>();
            for (int i = Integer.parseInt(year); i <=Integer.parseInt(yearend); i++) {
                //时间
                times.add(String.valueOf(i));
                //历史
                selectRequest.setColumns(new String[]{" yield"});
                StringBuilder builder = new StringBuilder();
                builder.append("1=1");
                if (!StringUtil.IsNullOrEmpty(cropname))
                    builder.append(" and cropname = '" + cropname + "'");
                if (!StringUtil.IsNullOrEmpty(strtybh))
                    builder.append(" and stationid = '" + strtybh + "'");
                if (!StringUtil.IsNullOrEmpty(year))
                    builder.append(" and year = '" + i+"'" );
                if (!StringUtil.IsNullOrEmpty(type))
                    builder.append(" and type = '" + type + "'");
                selectRequest.setParam(builder.toString());
                selectRequest.setSort(new String[]{"year"});
                selectParam.put("method", "cropyield_history");
                selectParam.put("sqlType", "select");
                selectParam.put("advCode", DbConfig.advCode);
                selectParam.put("param", JsonUtil.object2Json(selectRequest));
                String message = pc.processRequest(selectParam);
                infoList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<CropyieldHistory>>() {
                });
                Double cl = 0.0;
                if (infoList.size() != 0) cl = infoList.get(0).getYield();
                history.add(cl);
                //预报
                selectRequest = new RequestDataBySelect();
                selectParam = new HashMap<>();
                selectRequest.setColumns(new String[]{" yield"});
                builder = new StringBuilder();
                builder.append("1=1");
                if (!StringUtil.IsNullOrEmpty(cropname))
                    builder.append(" and cropname = '" + cropname + "'");
                if (!StringUtil.IsNullOrEmpty(strtybh))
                    builder.append(" and stationid = '" + strtybh + "'");
                if (!StringUtil.IsNullOrEmpty(year))
                    builder.append(" and year = '" + i + "'");
                if (!StringUtil.IsNullOrEmpty(type))
                    builder.append(" and type = '" + type + "'");
                selectRequest.setParam(builder.toString());
                selectRequest.setSort(new String[]{"year"});
                selectParam.put("method", "cropyield_fcst");
                selectParam.put("sqlType", "select");
                selectParam.put("advCode", DbConfig.advCode);
                selectParam.put("param", JsonUtil.object2Json(selectRequest));
                message = pc.processRequest(selectParam);
                List<CropyieldFcst> infoybList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<CropyieldFcst>>() {
                });
                cl = 0.0;
                if (infoybList.size() != 0) cl = infoybList.get(0).getYield();
                fast.add(cl);
            }
            arrayList.add(times);
            arrayList.add(history);
            arrayList.add(fast);
        } catch (Exception ex) {
            return new ResultObj("查询失败!", ex.getMessage(), false);
        }
        return new ResultObj("查询成功!", arrayList, true);
    }

    /**
     * @Description: 发育期预报
     * @Author: sunshine
     * @Date: 2021/7/27 12:40
     **/
    @Override
    public Object getnyfyqyb(String strtybh) {
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        Map<String, String> selectParam = new HashMap<>();
        List<CropGrowdateHistory> infoList = new ArrayList<>();
        try {
            selectRequest.setColumns(new String[]{" distinct cropname"});
            if (!StringUtil.IsNullOrEmpty(strtybh))
                selectRequest.setParam("stationid = '" + strtybh + "'");
            selectParam.put("method", "crop_growdate_history");
            selectParam.put("sqlType", "select");
            selectParam.put("advCode", DbConfig.advCode);
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            infoList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<CropGrowdateHistory>>() {
            });
        } catch (Exception ex) {
            return new ResultObj("查询失败!", ex.getMessage(), false);
        }
        return new ResultObj("查询成功!", infoList, true);
    }

    @Override
    public Object getFyqZwTypeByName(String strtybh, String cropname) {
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        Map<String, String> selectParam = new HashMap<>();
        List<CropGrowdateHistory> infoList = new ArrayList<>();
        try {
            selectRequest.setColumns(new String[]{" distinct type"});
            StringBuilder builder = new StringBuilder();
            builder.append("1=1");
            if (!StringUtil.IsNullOrEmpty(cropname))
                builder.append(" and cropname = '" + cropname + "'");
            if (!StringUtil.IsNullOrEmpty(strtybh))
                builder.append(" and stationid = '" + strtybh + "'");
            selectRequest.setParam(builder.toString());
            selectParam.put("method", "crop_growdate_history");
            selectParam.put("sqlType", "select");
            selectParam.put("advCode", DbConfig.advCode);
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            infoList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<CropGrowdateHistory>>() {
            });
        } catch (Exception ex) {
            return new ResultObj("查询失败!", ex.getMessage(), false);
        }
        return new ResultObj("查询成功!", infoList, true);
    }

    @Override
    public Object getFayuqiYb(String strtybh, String cropname, String year, String yearend, String type) {
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        ArrayList arrayList = new ArrayList();
        Map<String, String> selectParam = new HashMap<>();
        List<Object> FaYuQi = new ArrayList<>();
        List<CropGrowdateHistory> infoList = new ArrayList<>();
        if (StringUtil.IsNullOrEmpty(year) || StringUtil.IsNullOrEmpty(yearend))
            return new ResultObj("查询失败!", "年份不能为空!", false);
        try {
            List<String> times = new ArrayList<>();
            for (int i = Integer.parseInt(year); i <= Integer.parseInt(yearend); i++) {
                //时间
                times.add(String.valueOf(i));
                //历史
                selectRequest.setColumns(new String[]{"to_char(growdatedate,'MM-dd') as time","growdatename"});
                StringBuilder builder = new StringBuilder();
                builder.append("1=1");
                if (!StringUtil.IsNullOrEmpty(cropname))
                    builder.append(" and cropname = '" + cropname + "'");
                if (!StringUtil.IsNullOrEmpty(strtybh))
                    builder.append(" and stationid = '" + strtybh + "'");
                if (!StringUtil.IsNullOrEmpty(year))
                    builder.append(" and year = '" + i + "'");
                if (!StringUtil.IsNullOrEmpty(type))
                    builder.append(" and type = '" + type + "'");
                selectRequest.setParam(builder.toString());
                selectRequest.setSort(new String[]{"growdatedate"});
                selectParam.put("method", "crop_growdate_history");
                selectParam.put("sqlType", "select");
                selectParam.put("advCode", DbConfig.advCode);
                selectParam.put("param", JsonUtil.object2Json(selectRequest));
                String message = pc.processRequest(selectParam);
                infoList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<CropGrowdateHistory>>() {
                });
                if (infoList.size() != 0)
                    FaYuQi.add(infoList);
                //预报
                selectRequest = new RequestDataBySelect();
                selectParam = new HashMap<>();
                selectRequest.setColumns(new String[]{"to_char(forecastdate,'MM-dd') as time","growdatename"});
                builder = new StringBuilder();
                builder.append("1=1");
                if (!StringUtil.IsNullOrEmpty(cropname))
                    builder.append(" and cropname = '" + cropname + "'");
                if (!StringUtil.IsNullOrEmpty(strtybh))
                    builder.append(" and stationid = '" + strtybh + "'");
                if (!StringUtil.IsNullOrEmpty(year))
                    builder.append(" and year = '" + i + "'");
                if (!StringUtil.IsNullOrEmpty(type))
                    builder.append(" and type = '" + type + "'");
                selectRequest.setParam(builder.toString());
                selectRequest.setSort(new String[]{"forecastdate"});
                selectParam.put("method", "crop_growdate_fcst");
                selectParam.put("sqlType", "select");
                selectParam.put("advCode", DbConfig.advCode);
                selectParam.put("param", JsonUtil.object2Json(selectRequest));
                message = pc.processRequest(selectParam);
                List<CropGrowdateFcst> infoybList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<CropGrowdateFcst>>() {
                });
                FaYuQi.add(infoybList);
            }
        } catch (Exception ex) {
            return new ResultObj("查询失败!", ex.getMessage(), false);
        }
        return new ResultObj("查询成功!", FaYuQi, true);
    }

    /**
     * @Description: 农气发布图
     * @Author: sunshine
     * @Date: 2021/7/27 12:53
     **/
    @Override
    public Object getNyFabutu() {
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        Map<String, String> selectParam = new HashMap<>();
        List<StationInfo> infoList = new ArrayList<>();
        try {
//            selectRequest.setColumns(new String[]{"stationname", "lon", "lat", "farminfopubway"});
            StringBuilder builder = new StringBuilder();
            builder.append("lon != -1");
            selectRequest.setParam(builder.toString());
            selectParam.put("method", "station_info");
            selectParam.put("sqlType", "select");
            selectParam.put("advCode", DbConfig.advCode);
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            infoList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<StationInfo>>() {
            });
            for (StationInfo info : infoList) {
                String strdtvalue = info.getFarminfopubway().trim();//发布方式
                String strbmpname = "";
                if (strdtvalue.contains("DAB")) {
                    strbmpname = strbmpname + "1";
                } else {
                    strbmpname = strbmpname + "0";
                }
                if (strdtvalue.contains("显示屏")) {
                    strbmpname = strbmpname + "1";
                } else {
                    strbmpname = strbmpname + "0";
                }
                if (strdtvalue.contains("网络")) {
                    strbmpname = strbmpname + "1";
                } else {
                    strbmpname = strbmpname + "0";
                }
                if (strdtvalue.contains("电话") || strdtvalue.contains("短信")) {
                    strbmpname = strbmpname + "1";
                } else {
                    strbmpname = strbmpname + "0";
                }
                strdtvalue = strbmpname + ".gif";
                info.setFabuMode(strdtvalue);
            }
        } catch (Exception ex) {
            return new ResultObj("查询失败!", ex.getMessage(), false);
        }
        return new ResultObj("查询成功!", infoList, true);
    }

    /**
    * @Description: 作物分布图
    * @Author: sunshine
    * @Date: 2021/7/27 13:03
    **/
    @Override
    public Object getNyFenBuTu() {
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        Map<String, String> selectParam = new HashMap<>();
        List<StationInfo> infoList = new ArrayList<>();
        try {
            selectRequest.setColumns(new String[]{ "stationid", "lon", "lat", "stationname", "maincrop"});
            StringBuilder builder = new StringBuilder();
            builder.append("lon != -1");
            selectRequest.setParam(builder.toString());
            selectParam.put("method", "station_info");
            selectParam.put("sqlType", "select");
            selectParam.put("advCode", DbConfig.advCode);
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            infoList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<StationInfo>>() {
            });
        } catch (Exception ex) {
            return new ResultObj("查询失败!", ex.getMessage(), false);
        }
        return new ResultObj("查询成功!", infoList, true);
    }

}

class stationsum {
    public String num;

    public String type;

    public String getNum() {
        return num;
    }

    public void setNum(String num) {
        this.num = num;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
}